package com.jet.chat.command;

import com.jet.chat.dbquery.ChatQueryAddHistory;
import com.jet.chat.dbquery.ChatQueryAddHistoryParams;
import com.jet.chat.dbquery.ChatQueryUsers;
import com.jet.chat.dbquery.ChatQueryUsersResult;
import com.jet.chat.message.Message;
import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;

public class CCWhisper extends CCAbstract {

	@Override
	public void execute(CCParamsAbstract params) throws Exception {
		
		ChatServer chatServer = params.getChatServer();
		ChatSession chatSession = params.getChatSession();
		Message message = params.getMessage();
		
		String username = ((CCWhisperParams) params).getUsername();
		String content = ((CCWhisperParams) params).getContent();
		
		ChatQueryUsersResult users = (ChatQueryUsersResult) new ChatQueryUsers().execute(params.getChatServer().getDBConnectionService(), null);
		
		if (users.getUsers().containsKey(username)) {
			
			message.setContent(content);
			
			new ChatQueryAddHistory().execute(
				params.getChatServer().getDBConnectionService(),
				new ChatQueryAddHistoryParams(
					chatSession.getUserId(),
					users.getUsers().get(username),
					chatSession.getChannelName(),
					message
				)
			);
			
			ChatSession recieverSession = chatServer.getChannel(chatSession.getChannelName()).getSession(username);
			if (recieverSession == null ) {
				chatSession.getQueue().addMessage("server > no such reciever online. message will be stored");
			} else {
				message.setContent(chatSession.getUsername() + " whispers: " + message.getContent());
				recieverSession.getQueue().addMessage(message);
			}
		} else {
			params.getChatSession().getQueue().addMessage("server > no such reciever registered");
		}
		
	}

}
